import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

// 引入对应组件
import Home from '@/views/Home.vue'
import Page from '@/views/Page.vue'
import My from '@/views/My.vue'
import Cart from '@/views/Cart.vue'
import Topic from '@/views/Topic.vue'
import Search from '@/views/Search.vue'
import Detail from '@/views/Detail.vue'
import Kind from '@/views/Kind.vue'
import Buy from '@/views/Buy.vue'
import Address from '@/views/Address.vue'

// 路由配置
const routes = [
    { path: '/', redirect: '/home' },
    {
        path: '/home',
        component: Home,
        name: 'home',
        meta: { 'isShowTabBar': true }, // 是否显示底部tab的
        children: [
            {
                path: 'search', component: Search, meta: { 'isShowTabBar': false }
            }]
    },
    { path: '/page', component: Page, name: 'page', meta: { 'isShowTabBar': true } },
    { path: '/my', component: My, name: 'my', meta: { 'isShowTabBar': true } },
    { path: '/cart', component: Cart, name: 'cart', meta: { 'isShowTabBar': true } },
    { path: '/topic', component: Topic, name: 'topic', meta: { 'isShowTabBar': true } },
    { path: '/detail', component: Detail, name: 'detail', meta: { 'isShowTabBar': false } },
    { path: '/kind', component: Kind, name: 'kind', meta: { 'isShowTabBar': false } },
    { path: '/buy', component: Buy, name: 'buy', meta: { 'isShowTabBar': false } },
    { path: '/address', component: Address, name: 'address', meta: { 'isShowTabBar': false } },
]

const router = new VueRouter({
    mode: 'history',
    routes
})

// 该段代码不需要记，理解即可
//在vue - router在3.1.0版本之后，push和replace方法会返回一个promise对象，如果跳转到相同的路由，
// 就报promise uncaught异常
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch((err) => err);
};

// 全局前置路由-购物车
router.beforeEach((to, from, next) => {
    // 跳购物车之前判断是否登陆
    if (to.path == '/cart') {
        if (sessionStorage.getItem('token')) {
            next()
        } else {
            // 提示未登录
            Vue.prototype.$toast({
                message: '请先登录',
                position: 'bottom',
            });
            setTimeout(() => {
                next('/my')
            }, 2000);
        }
    } else { next() }
})

export default router